import type { CalculatePageList, ListItemProps, JumperProps } from "./type";
import { JUMP_NUM, JUMPER_BOUNDARY } from "./constant";

export const getPages = (total: number, pageSize: number): number => {
  return Math.floor(total / pageSize) + (total % pageSize > 0 ? 1 : 0);
};

export const calculatePageList: CalculatePageList = (
  total: number,
  current: number,
  pageSize: number
) => {
  let list = [];
  let amount = getPages(total, pageSize);
  if (amount < JUMPER_BOUNDARY) {
    for (let i = 0; i < amount; i++) {
      list.push({
        type: "page",
        pageNum: i + 1,
        active: i + 1 === current,
      } as ListItemProps);
    }
  } else {
    let first = {
      type: "page",
      pageNum: 1,
      active: current === 1,
    } as ListItemProps;

    let last = {
      type: "page",
      pageNum: amount,
      active: amount === current,
    } as ListItemProps;

    let jumpPrev = {
      type: "jump",
      jumpNum: JUMP_NUM,
      direction: "prev",
    } as JumperProps;

    let jumpNext = {
      type: "jump",
      jumpNum: JUMP_NUM,
      direction: "next",
    } as JumperProps;

    if (current < JUMP_NUM) {
      for (let i = 0; i < JUMP_NUM; i++) {
        list.push({
          type: "page",
          pageNum: i + 1,
          active: i + 1 === current,
        } as ListItemProps);
      }
      list.push(jumpNext, last);
    } else if (amount - current >= JUMP_NUM - 1) {
      list.push(
        first,
        jumpPrev,
        { type: "page", pageNum: current - 2, active: false } as ListItemProps,
        { type: "page", pageNum: current - 1, active: false } as ListItemProps,
        { type: "page", pageNum: current, active: true } as ListItemProps
      );
      list.push(
        { type: "page", pageNum: current + 1, active: false } as ListItemProps,
        { type: "page", pageNum: current + 2, active: false } as ListItemProps,
        jumpNext,
        last
      );
    } else {
      for (let i = amount - JUMP_NUM - 1; i < amount; i++) {
        list.push({
          type: "page",
          pageNum: i + 1,
          active: i + 1 === current,
        } as ListItemProps);
      }
      list.unshift(first, jumpPrev);
    }
  }
  return list;
};

export const validateInput = (value: string): number | "" => {
  return !value || isNaN(Number(value)) ? "" : Number(value);
};
